using AutoMapper;
using B.S.Data.MES.API.Applications.AICustomerService.Commands;
using B.S.Domain.AICustomerService;
using B.S.Domain.Dto.AICustomerServiceDTO;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace B.S.Data.MES.API.Applications.AICustomerService.CommandHandlers
{
    /// <summary>
    /// AI知识库命令处理器
    /// </summary>
    public class AIKnowledgeCommandHandler :
        IRequestHandler<CreateKnowledgeCommand, APIRequst<int>>,
        IRequestHandler<UpdateKnowledgeCommand, APIRequst<int>>,
        IRequestHandler<DeleteKnowledgeCommand, APIRequst<int>>,
        IRequestHandler<QueryKnowledgeCommand, APIRequst<APIPageing<List<KnowledgeResponseDTO>>>>,
        IRequestHandler<ToggleKnowledgeStatusCommand, APIRequst<int>>,
        IRequestHandler<SearchKnowledgeCommand, APIRequst<List<KnowledgeResponseDTO>>>
    {
        private readonly IBaseRepository<AIKnowledgeBase> _knowledgeRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AIKnowledgeCommandHandler> _logger;

        public AIKnowledgeCommandHandler(
            IBaseRepository<AIKnowledgeBase> knowledgeRepository,
            IMapper mapper,
            ILogger<AIKnowledgeCommandHandler> logger)
        {
            _knowledgeRepository = knowledgeRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 创建知识库
        /// </summary>
        public async Task<APIRequst<int>> Handle(CreateKnowledgeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var knowledge = new AIKnowledgeBase
                {
                    KnowledgeId = (int)YitIdHelper.NextId(),
                    Title = request.Knowledge.Title,
                    Question = request.Knowledge.Question,
                    Answer = request.Knowledge.Answer,
                    Category = request.Knowledge.Category,
                    Tags = request.Knowledge.Tags,
                    Priority = request.Knowledge.Priority,
                    MatchThreshold = request.Knowledge.MatchThreshold,
                    RelatedLinks = request.Knowledge.RelatedLinks,
                    IsEnabled = true,
                    UsageCount = 0,
                    CreateTime = DateTime.Now,
                    CreateName = "管理员",
                    isDel = false
                };

                await _knowledgeRepository.Add(knowledge);

                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = "知识库创建成功",
                    Data = knowledge.KnowledgeId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建知识库失败: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"创建知识库失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 更新知识库
        /// </summary>
        public async Task<APIRequst<int>> Handle(UpdateKnowledgeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var knowledge = await _knowledgeRepository.GetById(request.KnowledgeId);
                if (knowledge == null)
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = "知识库记录不存在",
                        Data = 0
                    };
                }

                knowledge.Title = request.Knowledge.Title;
                knowledge.Question = request.Knowledge.Question;
                knowledge.Answer = request.Knowledge.Answer;
                knowledge.Category = request.Knowledge.Category;
                knowledge.Tags = request.Knowledge.Tags;
                knowledge.Priority = request.Knowledge.Priority;
                knowledge.MatchThreshold = request.Knowledge.MatchThreshold;
                knowledge.RelatedLinks = request.Knowledge.RelatedLinks;
                knowledge.UpdateTime = DateTime.Now;
                knowledge.UpdateName = "管理员";

                await _knowledgeRepository.Update(knowledge);

                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = "知识库更新成功",
                    Data = 1
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新知识库失败: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"更新知识库失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 删除知识库
        /// </summary>
        public async Task<APIRequst<int>> Handle(DeleteKnowledgeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var knowledge = await _knowledgeRepository.GetById(request.KnowledgeId);
                if (knowledge == null)
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = "知识库记录不存在",
                        Data = 0
                    };
                }

                knowledge.isDel = true;
                knowledge.DeleteTime = DateTime.Now;
                knowledge.DeleteName = "管理员";

                await _knowledgeRepository.Update(knowledge);

                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = "知识库删除成功",
                    Data = 1
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除知识库失败: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"删除知识库失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 查询知识库
        /// </summary>
        public async Task<APIRequst<APIPageing<List<KnowledgeResponseDTO>>>> Handle(QueryKnowledgeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var query = _knowledgeRepository.GetAll();

                // 按条件筛选
                if (!string.IsNullOrEmpty(request.Query.Keyword))
                {
                    var keyword = request.Query.Keyword;
                    query = query.Where(x => x.Title.Contains(keyword) ||
                                           x.Question.Contains(keyword) ||
                                           x.Answer.Contains(keyword) ||
                                           (x.Tags != null && x.Tags.Contains(keyword)));
                }

                if (!string.IsNullOrEmpty(request.Query.Category))
                    query = query.Where(x => x.Category == request.Query.Category);

                if (request.Query.IsEnabled.HasValue)
                    query = query.Where(x => x.IsEnabled == request.Query.IsEnabled);

                // 排序
                query = query.OrderByDescending(x => x.Priority)
                           .ThenByDescending(x => x.UsageCount)
                           .ThenByDescending(x => x.CreateTime);

                // 分页
                var total = await query.CountAsync(cancellationToken);
                var knowledgeList = await query
                    .Skip((request.Query.PageIndex - 1) * request.Query.PageSize)
                    .Take(request.Query.PageSize)
                    .ToListAsync(cancellationToken);

                var responseList = _mapper.Map<List<KnowledgeResponseDTO>>(knowledgeList);

                var pageResult = new APIPageing<List<KnowledgeResponseDTO>>
                {
                    Total = (int)Math.Ceiling((double)total / request.Query.PageSize),
                    TotalCount = total,
                    Data = responseList
                };

                return new APIRequst<APIPageing<List<KnowledgeResponseDTO>>>
                {
                    Code = RequstCode.成功,
                    Msg = "查询知识库成功",
                    Data = pageResult
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询知识库失败: {Message}", ex.Message);
                return new APIRequst<APIPageing<List<KnowledgeResponseDTO>>>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询知识库失败: {ex.Message}",
                    Data = new APIPageing<List<KnowledgeResponseDTO>>
                    {
                        Total = 0,
                        TotalCount = 0,
                        Data = new List<KnowledgeResponseDTO>()
                    }
                };
            }
        }

        /// <summary>
        /// 启用/禁用知识库
        /// </summary>
        public async Task<APIRequst<int>> Handle(ToggleKnowledgeStatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var knowledge = await _knowledgeRepository.GetById(request.KnowledgeId);
                if (knowledge == null)
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = "知识库记录不存在",
                        Data = 0
                    };
                }

                knowledge.IsEnabled = request.IsEnabled;
                knowledge.UpdateTime = DateTime.Now;
                knowledge.UpdateName = "管理员";

                await _knowledgeRepository.Update(knowledge);

                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = $"知识库{(request.IsEnabled ? "启用" : "禁用")}成功",
                    Data = 1
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "切换知识库状态失败: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"切换知识库状态失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 搜索知识库（用于AI匹配）
        /// </summary>
        public async Task<APIRequst<List<KnowledgeResponseDTO>>> Handle(SearchKnowledgeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var keywords = request.Keyword.Split(' ', '，', '。', '？', '！', '、')
                    .Where(x => !string.IsNullOrWhiteSpace(x) && x.Length > 1)
                    .ToList();

                var query = _knowledgeRepository.GetAll()
                    .Where(x => x.IsEnabled);

                // 关键词匹配
                foreach (var keyword in keywords)
                {
                    query = query.Where(x => x.Question.Contains(keyword) ||
                                           x.Answer.Contains(keyword) ||
                                           x.Title.Contains(keyword) ||
                                           (x.Tags != null && x.Tags.Contains(keyword)));
                }

                var knowledgeList = await query
                    .OrderByDescending(x => x.Priority)
                    .ThenByDescending(x => x.UsageCount)
                    .Take(request.Limit)
                    .ToListAsync(cancellationToken);

                var responseList = _mapper.Map<List<KnowledgeResponseDTO>>(knowledgeList);

                return new APIRequst<List<KnowledgeResponseDTO>>
                {
                    Code = RequstCode.成功,
                    Msg = "搜索知识库成功",
                    Data = responseList
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索知识库失败: {Message}", ex.Message);
                return new APIRequst<List<KnowledgeResponseDTO>>
                {
                    Code = RequstCode.失败,
                    Msg = $"搜索知识库失败: {ex.Message}",
                    Data = new List<KnowledgeResponseDTO>()
                };
            }
        }
    }
}
